package servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.util.Collection;
import util.MyUtil;
@WebServlet("/uploadHttpMultiServlet")
@MultipartConfig(maxFileSize = 30*1024)//30kb
public class UploadHttpMultiServlet extends HttpServlet {
    private static final long serialVersionUID=1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应的内容类型
        response.setContentType("text/html;charset=utf-8");
        //取得输出对象
        PrintWriter out=response.getWriter();
        request.setCharacterEncoding("utf-8");
        //获取并输入文件描述
        String filediscription1=request.getParameter("filediscription1");
        out.println("输入文件1的描述："+filediscription1+"<br>");
        String filediscription2=request.getParameter("filediscription2");
        out.println("输入文件2的描述："+filediscription2+"<br>");
        //获取要存放的目录的完整路径
        File uploadFileDir=new File(getServletContext().getRealPath("/uploadFiles"));
        //如果获取的路径不存在则创造出来
        if(!uploadFileDir.exists())
            uploadFileDir.mkdir();
        //将上传的文件存到part集合中
        Collection<Part> parts=request.getParts();
        //遍历part集合
        for(Part part:parts){
            //如果当前part对象为空或不是文件域就遍历下一个
            if(part==null||!part.getName().contains("resPat")) {
                continue;
            }
            //获取原始文件名,绝对路径
            String oldName=MyUtil.getFileName(part);
            oldName=oldName.substring(oldName.lastIndexOf("\\")+1,oldName.length());
            //打印信息
            out.println("上传文件的原始名："+oldName+"<br>");
            out.println("上传文件的大小："+part.getSize()+"<br>");
            //如果获取的文件名不为空
            if(oldName!=null){
                //真正上传的操作，将文件上传到服务器之前指定的uploadFileDir目录下
                part.write(uploadFileDir+File.separator+oldName);
            }
            //打印文件上传路径
            out.println("文件上传到："+uploadFileDir+File.separator+oldName+"<br>");
        }
    }
}

